package com.yanze.mvvmlearndemo.moudles;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import com.google.gson.Gson;
import com.yanze.mvvmlearndemo.BR;
import com.yanze.mvvmlearndemo.R;
import com.yanze.mvvmlearndemo.adapter.ArticleAdapter;
import com.yanze.mvvmlearndemo.moudles.resp.ArticleEntity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BindListViewActivity extends AppCompatActivity {

    private ListView lv;
    private List<ArticleBean> mArticles;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ArticleAdapter<ArticleBean> mAdapter = new ArticleAdapter<>(BindListViewActivity.this, mArticles, R.layout.item_article, BR.article);
            lv.setAdapter(mAdapter);
        }
    };

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_list_view);
        mArticles = new ArrayList<>();
        lv = (ListView) findViewById(R.id.iv);
        requestNet();
    }

    //请求网络
    private void requestNet() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url("https://www.wuyouchaxian.com/001/v1/api/article?page_size=10&page_num=1&type=1")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                ArticleEntity entity = new Gson().fromJson(result, ArticleEntity.class);
                mArticles.addAll(entity.getData().getArticle());
                mHandler.sendEmptyMessage(0);
            }
        });
    }
}
